from flask import Flask, render_template, url_for, session, redirect, request
from .forms import ArticleForm
from werkzeug.datastructures import CombinedMultiDict
import os
from app.models import Article, Oplog, db
import datetime
from . import publish
import time
from ...blueprint import BASE_DIR


@publish.route('/', methods=('GET', 'POST'))
def publish():
    path = BASE_DIR + "/static/img/article/"
    print('publish函数开始')
    form = ArticleForm()
    if request.method == "GET":
        return render_template('publish.html', form=form)
    else:
        form = ArticleForm(CombinedMultiDict([request.form, request.files]))
        if form.validate():
            title = form.data['arc_name']
            content = form.data['arc_content']
            location = form.data['arc_location']
            longtitude = form.data['arc_longtitude']
            latitude = form.data['arc_latitude']
            author = session['username']
            upload_image = form.data["arc_file"]
            thisTime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
            if upload_image is None:
                url = "img/article/default.jpg"
            else:
                filename = title + time.strftime("%Y%m%d", time.localtime()) + '.jpg'
                file_path = path + filename
                upload_image.save(file_path)
                url = "img/article/" + filename
            click = 1

            i = Article(arc_name=title, arc_content=content, arc_author=author, arc_url=url, arc_location=location,
                        arc_longtitude=longtitude, arc_latitude=latitude, arc_click=click, arc_time=thisTime)
            ip = request.remote_addr
            opuser = session['username']
            op1 = "Article Publish"
            date = datetime.datetime.now()
            opt = Oplog(op_user=opuser, op=op1, IP=ip, op_date=date)
            db.session.add(opt)
            db.session.add(i)
            db.session.commit()
            ar = Article.query.filter_by(arc_name=title).first()
            arc_alike = 'like' + str(ar.id)
            ar.alike = arc_alike
            db.session.commit()
            return redirect("../")
        else:
            print(form.errors)
            return "fail"
